<template>
  <div class="withdrawal-container">
    <!-- 步骤1：出金方法选择 -->
    <div v-if="currentStep === 1" class="withdrawal-form">
      <div class="withdrawal-white-card">
        <div class="white-header">
          <span class="header-title">今すぐ出金申請する（クイック出金）</span>
        </div>
        
        <div class="white-content">
          <div class="content-layout">
            <div class="left-section">
              <h3 class="flow-title">ご利用の流れ</h3>
              <ul class="flow-list">
                <li>振込手数料：楽天銀行税込み100円、他行税込み500円、振込時に発生し、出金金額から差し引いてお振込します。</li>
                <li>出金審査：事務局にて締日から振込日までの間におこない、結果をメールにて通知します。</li>
                <li>取消・変更：締日を過ぎると、出金の取り消しや金額の変更（追加や除外）はできません。</li>
                <li>振込の反映時間：三井住友銀行の場合は通常10分以内に反映され、その他の銀行では30分以内に反映されます。</li>
              </ul>
            </div>
            
            <div class="right-section">
              <div class="amount-info">
                <div class="amount-display">
                  <span class="amount-text">出金可能額: <strong>{{ formatMoney(userBalance) }}円</strong> 満額: <strong>{{freezeMoney}}円</strong></span>
                </div>
              </div>
              <el-button class="withdrawal-button" @click="submitWithdrawalForm" :loading="loading"
                :disabled="loading">出金可能な残高をすべて出金申請する</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 步骤2：出金确认 -->
    <div v-if="currentStep === 2" class="withdrawal-confirm">
      <div class="withdrawal-white-card">
        <div class="white-header">
          <span class="header-title">今すぐ出金申請をする（クイック出金）</span>
        </div>
        
        <div class="white-content">
          <div class="content-layout">
            <div class="left-section">
              <h3 class="flow-title">ご利用の流れ</h3>
              <ul class="flow-list">
                <li>振込手数料：楽天銀行税込み100円、他行税込み500円、振込時に発生し、出金金額から差し引いてお振込します。</li>
                <li>出金審査：事務局にて締日から振込日までの間におこない、結果をメールにて通知します。</li>
                <li>取消・変更：締日を過ぎると、出金の取り消しや金額の変更（追加や除外）はできません。</li>
                <li>振込の反映時間：三井住友銀行の場合は通常10分以内に反映され、その他の銀行では30分以内に反映されます。</li>
              </ul>
            </div>
            
            <div class="right-section">
              <div class="amount-info">
                <div class="amount-display">
                  <span class="amount-text">出金可能額: <strong>{{ formatMoney(userBalance) }}円</strong><span v-if="freezeMoney > 0"> 凍った: <strong>{{ freezeMoney }}円</strong></span></span>
                </div>
              </div>
              <el-button class="withdrawal-button" @click="showWithdrawalDialog" :loading="loading"
                :disabled="loading || freezeMoney > 0">出金可能な残高をすべて出金申請する</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 步骤3：完成 -->
    <div v-if="currentStep === 3" class="withdrawal-complete">
      <el-card class="withdrawal-card">
        <template #header>
          <div class="card-header">
            <span>出金完了</span>
          </div>
        </template>

        <div class="complete-content">
          <el-result icon="success" title="出金リクエストが送信されました" sub-title="管理者が確認後、出金が処理されます。">
            <template #extra>
              <el-button type="primary" @click="goToTransactions">マイページ</el-button>
            </template>
          </el-result>
        </div>
      </el-card>
    </div>

    <!-- 出金金额输入弹窗 -->
    <el-dialog v-model="showDialog" title="出金" width="400px" :before-close="closeDialog">
      <div class="dialog-content">
        <div class="amount-input-section">
          <label>金額</label>
          <el-input 
            v-model="withdrawalAmount" 
            type="number"
            class="amount-input-field"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">キャンセル</el-button>
          <el-button type="primary" @click="confirmWithdrawalAmount">決定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 金额不足错误弹窗 -->
    <el-dialog v-model="showErrorDialog" title="" width="400px" :show-close="false">
      <div class="error-dialog-content">
        <div class="error-icon">⚠</div>
        <div class="error-message">引き出し金額を入力してください</div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="closeErrorDialog">決定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 金额足够成功弹窗 -->
    <el-dialog v-model="showSuccessDialog" title="" width="400px" :show-close="false">
      <div class="success-dialog-content">
        <div class="success-icon">✓</div>
        <div class="success-message">20分以内に入金されますので、ご確認ください</div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="closeSuccessDialog">決定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { InfoFilled, Warning } from '@element-plus/icons-vue'
import { withdrawalApi, userApi } from '../../../api/index'

const router = useRouter()
const currentStep = ref(2)
const withdrawalFormRef = ref(null)
const loading = ref(false)
const withdrawalId = ref('')
const userBalance = ref(0)
const maxWithdrawalAmount = ref(0)
const freezeMoney = ref(null)
const showDialog = ref(false)
const withdrawalAmount = ref('')
const showSuccessDialog = ref(false)
const showErrorDialog = ref(false)

// 银行信息
const bankInfo = ref({
  fee: 0,
  actualAmount: 0
})

// 表单数据
const withdrawalForm = reactive({
  withdrawalMethod: 'jpy',
  amount: ''
})

// 表单验证规则
const rules = {
  withdrawalMethod: [
    { required: true, message: '出金方法を選択してください', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '金額を入力してください', trigger: 'blur' },
    { type: 'number', min: 1, message: '金額は1以上である必要があります', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value > maxWithdrawalAmount.value) {
          callback(new Error(`金額は${maxWithdrawalAmount.value}以下である必要があります`))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户余额
const getUserBalance = async () => {
  try {
    loading.value = true
    const res = await userApi.getBankAccount()
    if (res.code === 1 && res.data) {
      console.log(res.data)
      userBalance.value = parseFloat(res.data.money) || 0
      maxWithdrawalAmount.value = userBalance.value
      freezeMoney.value = res.data.freeze_money
      console.log(freezeMoney.value)
    } else {
      ElMessage.error('残高情報の取得に失敗しました')
    }
  } catch (error) {
    console.error('获取用户余额失败:', error)
    ElMessage.error('残高情報の取得に失敗しました')
  } finally {
    loading.value = false
  }
}

// 格式化金额
const formatMoney = (amount) => {
  return amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 提交表单
const submitWithdrawalForm = async () => {
  try {
    loading.value = true
    
    // 设置提款金额为用户的全部余额
    withdrawalForm.amount = userBalance.value
    
    // 模拟银行信息
    bankInfo.value = {
      fee: 100, // 假设手续费为100日元
      actualAmount: withdrawalForm.amount - 100
    }
    
    // 生成出金ID并进入确认页面
    withdrawalId.value = 'WD' + Date.now()
    currentStep.value = 2
    
  } catch (error) {
    console.error('提交出金请求失败:', error)
    ElMessage.error('出金リクエストの送信に失敗しました')
  } finally {
    loading.value = false
  }
}

// 确认出金
const confirmWithdrawal = async () => {
  try {
    loading.value = true
    
    // 设置提款金额为用户的全部可用余额
    withdrawalForm.amount = userBalance.value

    // 这里可以添加确认出金的API调用
    // 目前直接进入完成页面
    setTimeout(() => {
      loading.value = false
      ElMessage.success('出金リクエストが送信されました')
      currentStep.value = 3
    }, 500)
  } catch (error) {
    console.error('确认出金失败:', error)
    ElMessage.error('出金確認に失敗しました')
  } finally {
    loading.value = false
  }
}

// 显示出金弹窗
const showWithdrawalDialog = () => {
  if (freezeMoney.value === 0) {
    showDialog.value = true
    withdrawalAmount.value = ''
  }
}

// 确认出金金额
const confirmWithdrawalAmount = async () => {
  const amount = parseFloat(withdrawalAmount.value)
  if (!amount || amount <= 0) {
    ElMessage.error('出金金額を入力してください')
    return
  }

  const res = await withdrawalApi.verifyWithdrawal({
          payment_method: withdrawalForm.withdrawalMethod,
          money: amount
        })
  console.log(res)
  showDialog.value = false
  
  if (amount > userBalance.value) {
    // 金额不足，显示错误弹窗
    showErrorDialog.value = true
  } else {
    // 金额足够，显示成功弹窗
    showSuccessDialog.value = true
  }
}

// 关闭弹窗
const closeDialog = () => {
  showDialog.value = false
  withdrawalAmount.value = ''
}

// 关闭成功弹窗
const closeSuccessDialog = () => {
  showSuccessDialog.value = false
}

// 关闭错误弹窗
const closeErrorDialog = () => {
  showErrorDialog.value = false
}

// 跳转到交易记录页面
const goToTransactions = () => {
  router.push('/user/transactions')
}

// 页面加载时获取用户余额
onMounted(() => {
  getUserBalance()
})
</script>

<style scoped>
.withdrawal-container {
  padding: 20px;
  max-width: 1080px;
  margin: 0 auto;
}

.withdrawal-steps {
  margin-bottom: 30px;
}

.withdrawal-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.usage-flow {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

.usage-flow h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
  font-size: 16px;
}

.usage-flow ul {
  margin: 0;
  padding-left: 20px;
}

.usage-flow li {
  margin-bottom: 8px;
  line-height: 1.5;
  color: #606266;
}

.amount-input {
  width: 100%;
  display: flex;
  align-items: center;
}

.currency {
  margin-left: 10px;
  font-size: 16px;
}

.balance-info {
  margin-top: 5px;
  font-size: 14px;
  color: #606266;
}

.confirm-message {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 20px;
}

.highlight {
  color: #409EFF;
  font-weight: bold;
}

/* 白色卡片样式 */
.withdrawal-white-card {
  background: white;
  border-radius: 3px;
  overflow: hidden;
  box-shadow: 0 0px 5px rgba(0, 0, 0, 0.12);
  margin: 0px 0;
  border: 1px solid #e0e0e0;
}

.white-header {
  background: rgb(85, 186, 233);
  padding: 10px 20px;
  color: white;
}

.header-title {
  color: white;
  font-size: 14px;
  font-weight: 500;
}

.white-content {
  padding: 20px;
}

.content-layout {
  display: flex;
  gap: 30px;
  align-items: flex-start;
}

.left-section {
  flex: 1;
}

.right-section {
  min-width: 300px;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.flow-title {
  color: #333;
  font-size: 12px;
  margin-bottom: 15px;
  font-weight: 500;
}

.flow-list {
  padding-left: 20px;
  margin: 0;
}

.flow-list li {
  color: #666;
  margin-bottom: 5px;
  line-height: 1.15;
  font-size: 12px;
}

.amount-info {
  margin-bottom: 20px;
  text-align: right;
}

.amount-display {
  text-align: right;
  margin-bottom: 15px;
}

.amount-text {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.amount-text strong {
  color: #333;
  font-weight: bold;
}

.withdrawal-button {
  background: linear-gradient(135deg, #4FC3F7 0%, #29B6F6 100%);
  border: none;
  color: white;
  padding: 12px 24px;
  font-size: 14px;
  border-radius: 4px;
  min-width: 280px;
  margin-top: -30px;
}

.withdrawal-button:disabled {
  background: #A0CFFF !important;
  color: white !important;
  cursor: not-allowed !important;
  opacity: 0.8;
}

.withdrawal-btn:hover {
  background-color: #1565C0;
  border-color: #1565C0;
}

.confirm-details {
  margin-bottom: 20px;
}

.confirm-details h3 {
  font-size: 16px;
  margin-bottom: 10px;
  color: #333;
}

.withdrawal-rules {
  padding-left: 20px;
  margin: 0;
}

.withdrawal-rules li {
  margin-bottom: 8px;
  line-height: 1.5;
  font-size: 14px;
  color: #606266;
}

.withdrawal-amount-box {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  margin-top: 20px;
}

.amount-header {
  font-size: 16px;
  margin-bottom: 15px;
  color: #333;
}

.amount-value {
  font-weight: bold;
  color: #409EFF;
  font-size: 18px;
}

.confirm-button {
  width: 100%;
  margin-top: 10px;
  font-size: 16px;
  padding: 12px 0;
}

.bank-info {
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.bank-info-item {
  display: flex;
  margin-bottom: 10px;
}

.label {
  width: 100px;
  font-weight: bold;
  color: #606266;
}

.value {
  flex: 1;
}

.notice-info {
  margin-top: 15px;
  padding: 10px 15px;
  background-color: #fef0f0;
  border-radius: 4px;
  border-left: 4px solid #f56c6c;
}

.notice-info p {
  display: flex;
  align-items: center;
  margin: 8px 0;
  color: #606266;
  line-height: 1.5;
}

.notice-info .el-icon {
  margin-right: 8px;
  color: #f56c6c;
}

/* 弹窗样式 */
.dialog-content {
  padding: 20px 0;
}

.amount-input-section {
  margin-bottom: 20px;
}

.amount-input-section label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.amount-input-field {
  width: 100%;
}

.dialog-footer {
  text-align: center;
}

.dialog-footer .el-button {
  margin: 0 10px;
  min-width: 80px;
}

/* 错误弹窗样式 */
.error-dialog-content {
  text-align: center;
  padding: 20px 0;
}

.error-icon {
  font-size: 48px;
  color: #f56c6c;
  margin-bottom: 16px;
}

.error-message {
  font-size: 16px;
  color: #333;
  line-height: 1.5;
}

/* 成功弹窗样式 */
.success-dialog-content {
  text-align: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 48px;
  color: #67c23a;
  margin-bottom: 16px;
  font-weight: bold;
}

.success-message {
  font-size: 16px;
  color: #333;
  line-height: 1.5;
}

/* 移动端自适应样式 */
@media (max-width: 768px) {
  .withdrawal-container {
    padding: 10px;
    max-width: 100%;
  }

  .content-layout {
    flex-direction: column;
    gap: 20px;
  }

  .left-section {
    order: 2;
  }

  .right-section {
    order: 1;
    min-width: auto;
    width: 100%;
    align-items: stretch;
  }

  .amount-display {
    text-align: center;
    margin-bottom: 15px;
  }

  .amount-text {
    font-size: 16px;
    text-align: center;
  }

  .withdrawal-button {
    width: 100%;
    min-width: auto;
    padding: 15px 20px;
    font-size: 16px;
  }

  .withdrawal-button:disabled {
    background: #B3E5FC !important;
    color: #666 !important;
    cursor: not-allowed !important;
    opacity: 0.8;
  }

  .flow-title {
    font-size: 18px;
    margin-bottom: 12px;
  }

  .flow-list li {
    font-size: 15px;
    margin-bottom: 6px;
    line-height: 1.4;
  }

  .white-header {
    padding: 12px 15px;
  }

  .header-title {
    font-size: 16px;
  }

  .white-content {
    padding: 15px;
  }

  /* 弹窗移动端适配 */
  .el-dialog {
    width: 90% !important;
    margin: 0 auto;
  }

  .dialog-content {
    padding: 15px 0;
  }

  .amount-input-section label {
    font-size: 16px;
    margin-bottom: 10px;
  }

  .amount-input-field .el-input__inner {
    font-size: 16px;
    padding: 12px;
  }

  .dialog-footer .el-button {
    min-width: 100px;
    padding: 12px 20px;
    font-size: 16px;
  }

  .error-dialog-content,
  .success-dialog-content {
    padding: 25px 0;
  }

  .error-icon,
  .success-icon {
    font-size: 60px;
    margin-bottom: 20px;
  }

  .error-message,
  .success-message {
    font-size: 18px;
    padding: 0 10px;
  }
}

@media (max-width: 480px) {
  .withdrawal-container {
    padding: 5px;
  }

  .white-content {
    padding: 10px;
  }

  .content-layout {
    gap: 15px;
  }

  .flow-list {
    padding-left: 15px;
  }

  .flow-list li {
    font-size: 14px;
    margin-bottom: 4px;
    line-height: 1.3;
  }

  .amount-text {
    font-size: 14px;
  }

  .withdrawal-button {
    padding: 12px 15px;
    font-size: 14px;
  }

  .withdrawal-button:disabled {
    background: #B3E5FC !important;
    color: #666 !important;
    cursor: not-allowed !important;
    opacity: 0.8;
  }

  .header-title {
    font-size: 15px;
  }

  /* 超小屏幕弹窗适配 */
  .el-dialog {
    width: 95% !important;
  }

  .error-message,
  .success-message {
    font-size: 16px;
  }
}
</style>